import sys
import os
from PySide6.QtWidgets import *
from PySide6.QtGui import *
from PySide6.QtCore import *
from PySide6.QtSql import *

class Demo(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.parent = parent
        self.dbFile=os.path.join(self.parent.getAppDir(),'test.db')
        layout = QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        
        toolBar=QToolBar()
        self.sqlEdit=QLineEdit()
        self.sqlEdit.setText('SELECT * FROM User ORDER BY id ASC')
        toolBar.addWidget(self.sqlEdit)

        btn=QPushButton('Query')
        btn.clicked.connect(self.Query)
        toolBar.addWidget(btn)
        layout.addWidget(toolBar)

        self.model=QSqlQueryModel()
        self.tableView=QTableView()
        self.tableView.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows)#行选择
        self.tableView.setModel(self.model)
        layout.addWidget(self.tableView)

        self.setLayout(layout)
    def Query(self):
        if len(self.sqlEdit.text())==0:return
        db=QSqlDatabase().addDatabase("QSQLITE")
        db.setDatabaseName(self.dbFile)
        sql=self.sqlEdit.text()
        db.open()
        self.model.setQuery(sql,db)
        #self.model.setHeaderData(0,Qt.Orientation.Horizontal,'主键')#重命名列头
        #self.model.setHeaderData(1,Qt.Orientation.Horizontal,'姓名')#重命名列头
        db.close()
        self.parent.OnShowMessage(f'Exec sql:{sql}')
def runDemo(parent):
    wigdet =  Demo(parent)
    return wigdet